package com.android.baseconfig.data.http.okhttp.interceptor;

import android.text.TextUtils;

import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.config.HttpConstant;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.data.http.AppNetDelegate;
import com.android.baseconfig.data.http.okhttp.api.ApiImpl;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: TokenInterceptor <br>
 * 作者: lei <br>
 * 日期: 2021/12/26 <br>
 */
public class TokenInterceptor implements Interceptor {
    private static final String TAG = "TokenInterceptor";

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Response response = chain.proceed(request);


        // 判断token是否过期
        if (isTokenExpired(response)) {
            Logc.d(TAG, "response.code = " + response.code());
            Logc.d(TAG, "token 失效, 刷新token重新请求数据");

            // 同步请求方式，获取最新的Token
            String newToken = getNewToken();
            if (!TextUtils.isEmpty(newToken)) {
                BaseSharedPreferences.setString(AppNetDelegate.getAppContext(), HttpConstant.TOKEN, newToken);

                // 使用新的Token，创建新的请求
                Request newRequest = chain.request()
                        .newBuilder()
                        .header(HttpConstant.TOKEN, newToken)
                        .build();

                // 重新请求
                return chain.proceed(newRequest);
            }
        }

        return response;
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        return response.code() == 401 || response.code() == 40101;
    }

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    private String getNewToken() throws IOException {
        String oldToken = BaseSharedPreferences.getString(AppNetDelegate.getAppContext(), HttpConstant.TOKEN);
        if (TextUtils.isEmpty(oldToken)) {
            RxBus3.getInstance().post("EXIT_LOGIN");
            return null;
        }
        // 通过获取token的接口，同步请求接口
        Call<BaseApiResult<String>> call = ApiImpl.getInstance().getToken(oldToken);
        BaseApiResult<String> apiResult = call.execute().body();
        if (apiResult != null) {
            Logc.i(TAG, "new token = " + apiResult.data);
            return apiResult.data;
        }
        return null;
    }

}